package com.ghpt.service.impl;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ghpt.component.CsvParser;
import com.ghpt.mapper.SolarRadiationMapper;
import com.ghpt.util.SpringContextUtils;
import com.ghpt.pojo.UpdatableEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.beans.Introspector;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class BatchUpdateService {

    @Autowired
    private CsvParser csvParser;
    @Autowired
    private SolarRadiationMapper SolarRadiationMapper;

    @Transactional
    public <T extends UpdatableEntity> void batchUpdate(MultipartFile file, Class<T> clazz) throws Exception {
        List<Map<String, Object>> csvData = csvParser.parseCsv(file);

        // BaseMapper<T> mapper = (BaseMapper<T>) SpringContextUtils.getBean(clazz.getSimpleName() + "Mapper");
        // 使用首字母小写的类名
        String beanName = Introspector.decapitalize(clazz.getSimpleName() + "Mapper");
        System.out.println("尝试获取的bean名称: " + beanName);
        BaseMapper<T> mapper = (BaseMapper<T>) SpringContextUtils.getBean(beanName);

        List<T> entities = csvData.stream().map(map -> {
            T entity = null;
            try {
                entity = clazz.getDeclaredConstructor().newInstance();
                entity.setId((Long) map.get("id"));
                entity.setValue((Double) map.get("value"));
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("实体实例化失败", e);
            }
            return entity;
        }).collect(Collectors.toList());

        // 批量更新
        entities.forEach(entity -> {
            mapper.updateById(entity);
        });
    }
}